﻿/*
 * Copyright (c) 2009, Thiago M. Sayao <thiago.sayao@gmail.com>
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 *  * Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  * Neither the name of the author nor the names of its contributors may be 
 *    used to endorse or promote products derived from this software without 
 *    specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 * POSSIBILITY OF SUCH DAMAGE.
 */

using System.Web;
using System.Web.Caching;
using System.Data.SqlClient;
using DotNetBurner.Model;
using DotNetBurner.Core;
using DotNetBurner.Web;

namespace DotNetBurner.Model
{
    public class CachedRepository : Repository
    {
        delegate StoryList StoryListDelegate();

        public CachedRepository(string connStr)
            : base(connStr)
        {

        }

        /*
         * This is commented out because it's we now cache the entire partial view 
        public override IEnumerable<Category> GetCategories()
        {
            IEnumerable<Category> categories;

            if (Cache.TryGet("categories", out categories))
            {
                return categories;
            }

            categories = base.GetCategories();

            Cache.CacheData("categories", "Categories", categories);

            return categories;
        }

        public override IEnumerable<Tag> GetTags(int top)
        {
            string key = "tags-{0}".FormatWith(top);

            IEnumerable<Tag> tags;

            if (Cache.TryGet(key, out tags))
                return tags;

            tags = base.GetTags(top);

            Cache.CacheData(key, "TopTags", tags);

            return tags;
        }

        public override TopUsers GetTopLeaders(int start, int max)
        {
            string key = "topleaders-{0}-{1}".FormatWith(start, max);

            TopUsers topusers;

            if (Cache.TryGet(key, out topusers))
                return topusers;

            topusers = base.GetTopLeaders(start, max);

            Cache.CacheData(key, "TopUsers", topusers);

            return topusers;
        }

        public override TopUsers GetTopMovers(int start, int max)
        {
            string key = "topmovers-{0}-{1}".FormatWith(start, max);

            TopUsers topusers;

            if (Cache.TryGet(key, out topusers))
                return topusers;

            topusers = base.GetTopMovers(start, max);

            Cache.CacheData(key, "TopUsers", topusers);

            return topusers;
        }
        */

        public override int GetVoteCountByUrl(string url)
        {
            string key = "votebyurl-{0}".FormatWith(url);
            int voteCount = 0;

            if (Cache.TryGet(key, out voteCount))
                return voteCount;

            voteCount = base.GetVoteCountByUrl(url);
            Cache.CacheData(key, "VoteButton", voteCount);

            return voteCount;
        }

        public override int GetUserId(object identifier)
        {
            string key = "cu-{0}".FormatWith(identifier);

            int userId = 0;

            if (Cache.TryGet(key, out userId))
                return userId;

            userId = base.GetUserId(identifier);

            Cache.CacheData(key, "User", userId);

            return userId;
        }

        /*
         * This works this way:
         * 
         * It caches all stories. 
         * If user is 0 (anonymous) there is no need to update the Voted/Burned status because anonymous users cannot vote
         * If user is != 0 then we use the same listing, but update the Voted status
         * If a story was submitted after it was cached, then the cache is invalidated
         */
        public override StoryList GetPublishedStoriesForAllCategory(int userId, int sortDays, int start, int max)
        {
            string key = "published-{0}-{1}-{2}".FormatWith(sortDays, start, max);

            return PrepareStoriesFromCache(key, userId,
                                           () => BaseGetPublishedStoriesForAllCategory(userId, sortDays, start, max));
        }

        StoryList BaseGetPublishedStoriesForAllCategory(int userId, int sortDays, int start, int max)
        {
            return base.GetPublishedStoriesForAllCategory(userId, sortDays, start, max);
        }

        public override StoryList GetUpcomingStories(int userId, int sortDays, int start, int max)
        {
            string key = "upcoming-{0}-{1}-{2}".FormatWith(sortDays, start, max);

            return PrepareStoriesFromCache(key, userId,
                                           () => BaseGetUpcomingStories(userId, sortDays, start, max));
        }

        StoryList BaseGetUpcomingStories(int userId, int sortDays, int start, int max)
        {
            return base.GetUpcomingStories(userId, sortDays,  start, max);
        }

        public override StoryList GetPublishedStoriesForCategory(int userId, int categoryId, int sortDays, int start, int max)
        {
            string key = "published-{0}-{1}-{2}-{3}".FormatWith(categoryId, sortDays, start, max);

            return PrepareStoriesFromCache(key, userId,
                                           () =>
                                           BaseGetPublishedStoriesForCategory(userId, categoryId, sortDays, start, max));
        }

        StoryList BaseGetPublishedStoriesForCategory(int userId, int categoryId, int sortDays, int start, int max)
        {
            return base.GetPublishedStoriesForCategory(userId, categoryId, sortDays, start, max);
        }

        public override StoryList GetStoriesForTag(int userId, int tagId, int sortDays, int start, int max)
        {
            string key = "storiesfortag-{0}-{1}-{2}-{3}".FormatWith(tagId, sortDays, start, max);

            return PrepareStoriesFromCache(key, userId, () => BaseGetStoriesForTag(userId, tagId, sortDays, start, max));
        }

        StoryList BaseGetStoriesForTag(int userId, int tagId, int sortDays, int start, int max)
        {
            return base.GetStoriesForTag(userId, tagId, sortDays, start, max);
        }

        public override StoryList GetStoriesPostedByUser(int userId, int postedByUserId, int sortDays, int start, int max)
        {
            string key = "storiesbyuser-{0}-{1}-{2}-{3}".FormatWith(postedByUserId, sortDays, start, max);

            return PrepareStoriesFromCache(key, userId,
                                           () =>
                                           BaseGetStoriesPostedByUser(userId, postedByUserId, sortDays, start, max));
        }

        StoryList BaseGetStoriesPostedByUser(int userId, int postedByUserId, int sortDays, int start, int max)
        {
            return base.GetStoriesPostedByUser(userId, postedByUserId, sortDays, start, max);
        }

        StoryList PrepareStoriesFromCache(string key, int userId, StoryListDelegate del)
        {
            StoryList stories;

            if (Cache.TryGet(key, out stories))
            {
                UpdateVoteStatusForStories(stories, userId);

                return stories;
            }

            stories = del();

            Cache.CacheData(key, "StoryList", stories);

            return stories;
        }

        /*
         *  We do not cache stories by user, because it would not make any sense, so 
         *  we just update the story listing for each different user.
         *  
         *  Sometimes i like my own ideas so much...
         */
        void UpdateVoteStatusForStories(StoryList stories, int userId)
        {
            //if its not authenticated, there is no need to update from the database
            if (userId == 0)
            {
                foreach (Story story in stories)
                {
                    story.HasVoted = false;
                }

                return;
            }

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                SetUserHasVotedInStories(conn, stories, userId);
            }
        }

        public static Cache Cache
        {
            get
            {
                return HttpRuntime.Cache;
            }
        }
    }
}
